package org.kojo.tdrm.service.notic;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.utils.App;
import org.kojo.tdrm.utils.AppTokenUtils;
import org.kojo.tdrm.utils.HttpUtils;

public class FBNotification implements INotification {
	private static Logger log = Logger
			.getLogger(FBNotification.class.getName());

	public static String PROFILE_ID = "PROFILE_ID";
	public static String REM_TASKS = "REM_TASKS";
	private Map params = new HashMap(0);

	@Override
	public int publish() {
		String profileId = (String) params.get(PROFILE_ID);
		Set<Task> remTasks = (Set<Task>) params.get(REM_TASKS);
		String msg = "Reminder for " + remTasks.size() + " tasks.\n";
		for (Task t : remTasks) {
			msg += "Task:" + t.getName() + " Due Date:" + t.getDueDate()
					+ " \n";
		}

		try {
			AppTokenUtils appToken = AppTokenUtils.getInstance();
			String token = appToken.getToken();
			log.fine("token=" + token);
			// String res1 =
			// u.getUrlContent("https://graph.facebook.com/app/insights?access_token="+token);
			// System.out.println("res1="+res1);
			String encodedMsg = URLEncoder.encode(msg, "UTF-8");
			if (profileId != null && !"".equals(profileId)) {
				String feed = "https://graph.facebook.com/" + profileId
						+ "/feed?access_token=" + token;
				feed += "&privacy=SELF";
				feed += "&message=" + encodedMsg;
				HttpUtils u = new HttpUtils();
				String resp = u.postUrlContent(feed);
				log.fine(resp);
			}
		} catch (IOException e) {
			log.log(Level.WARNING, "Cannot alert for profile=" + profileId, e);
		}
		return 0;
	}

	@Override
	public void setParams(Map params) {
		this.params = params;

	}

}
